const App = getApp();
const wxParse = require("../../wxParse/wxParse.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {

    isLoading: true,
    dataType: 1,
    page: 1,
    no_more: false,


    indicatorDots: true, // 是否显示面板指示点
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    duration: 800, // 滑动动画时长

    currentIndex: 1, // 轮播图指针
    floorstatus: false, // 返回顶部
    showView: true, // 显示商品规格

    detail: {}, // 详情信息
    stars_num:1,//星星数量
    couponText: false,//优惠券详情

    // 分享按钮组件
    share: {
      show: false,
      cancelWithMask: true,
      cancelText: '关闭',
      actions: [
      //   {
      //   name: '生成商品海报',
      //   className: 'action-class',
      //   loading: false
      // }, 
      {
        name: '发送给朋友',
        openType: 'share'
      }],
      // 商品海报
      showPopup: false,
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(e) {
    //console.log(e.id);
    let _this = this;
    _this.setData({
      id: e.id,
      page_sex: e.page_sex,
      app_root: App.root
    });
    // 获取详情
    _this.getDetail();
    // 获取当前用户信息
    this.getUserDetail();
  },

  /**
   * 获取当前用户信息
   */
  getUserDetail: function () {
    let _this = this;
    App._get('user.index/detail', {}, function (result) {
      console.log(result.data);
      _this.setData(result.data);
    });
  },

  /**
   * 获取详情
   */
  getDetail: function(isNextPage, page) {
    let _this = this;
    App._get('enroll/detail', {
      id: _this.data.id,
      page: page || 1,
    }, function(result) {
      console.log(result);
      // 初始化商品详情数据
      let data = _this.initDetailData(result.data, isNextPage);
      _this.setData(data);

      //console.log(_this.data.detail);
    });
  },

  /**
   * 初始化商品详情数据
   */
  initDetailData: function (data, isNextPage) {
    let _this = this;
    data['isLoading'] = false;
    // 列表数据
    let dataList = this.data.enroll_vote_res;
    if (isNextPage == true && (typeof dataList !== 'undefined')) {
      data.enroll_vote_res.data = dataList.data.concat(data.enroll_vote_res.data);
    }
    // 富文本转码
    // if (data.detail.content.length > 0) {
    //   wxParse.wxParse('content', 'html', data.detail.content, _this, 0);
    // }
    //let images = [];
    for (let j = 0; j < data.detail.images.length; j++) {
      data.detail.images[j] = App.root + data.detail.images[j];
    }
    
    return data;
  },

  // 点击详情页 展开/搜索
  clickcontent:function(){
    
    if (this.data.couponText == false){
      this.setData({
        couponText: true
      });
    }else{
      this.setData({
        couponText: false
      });
    }
  },

  /**
   * 初始化商品多规格
   */
  initManySpecData: function(data) {
    for (let i in data.spec_attr) {
      for (let j in data.spec_attr[i].spec_items) {
        if (j < 1) {
          data.spec_attr[i].spec_items[0].checked = true;
          this.goods_spec_arr[i] = data.spec_attr[i].spec_items[0].item_id;
        }
      }
    }
    return data;
  },

  /**
   * 点击切换不同规格
   */
  modelTap: function(e) {
    let attrIdx = e.currentTarget.dataset.attrIdx,
      itemIdx = e.currentTarget.dataset.itemIdx,
      specData = this.data.specData;
    for (let i in specData.spec_attr) {
      for (let j in specData.spec_attr[i].spec_items) {
        if (attrIdx == i) {
          specData.spec_attr[i].spec_items[j].checked = false;
          if (itemIdx == j) {
            specData.spec_attr[i].spec_items[itemIdx].checked = true;
            this.goods_spec_arr[i] = specData.spec_attr[i].spec_items[itemIdx].item_id;
          }
        }
      }
    }
    this.setData({
      specData
    });
    // 更新商品规格信息
    this.updateSpecGoods();
  },

  /**
   * 更新商品规格信息
   */
  updateSpecGoods: function() {
    let spec_sku_id = this.goods_spec_arr.join('_');

    // 查找skuItem
    let spec_list = this.data.specData.spec_list,
      skuItem = spec_list.find((val) => {
        return val.spec_sku_id == spec_sku_id;
      });

    // 记录goods_sku_id
    // 更新商品价格、划线价、库存
    if (typeof skuItem === 'object') {
      this.setData({
        goods_sku_id: skuItem.spec_sku_id,
        goods_price: skuItem.form.goods_price,
        line_price: skuItem.form.line_price,
        stock_num: skuItem.form.stock_num,
        image_path: skuItem.form.image_id > 0 ? skuItem.form.image_path : this.data.detail.image[0].file_path
      });
    }
  },

  /**
   * 设置轮播图当前指针 数字
   */
  setCurrent: function(e) {
    this.setData({
      currentIndex: e.detail.current + 1
    });
  },

  /**
   * 控制商品规格/数量的显示隐藏
   */
  onChangeShowState: function() {
    this.setData({
      showView: !this.data.showView
    });
  },

  /**
   * 返回顶部
   */
  goTop: function(t) {
    this.setData({
      scrollTop: 0
    });
  },

  /**
   * 显示/隐藏 返回顶部按钮
   */
  scroll: function(e) {
    this.setData({
      floorstatus: e.detail.scrollTop > 200
    })
  },

  /**
   * 增加商品数量
   */
  up: function() {
    this.setData({
      goods_num: ++this.data.goods_num
    })
  },

  /**
   * 减少商品数量
   */
  down: function() {
    if (this.data.goods_num > 1) {
      this.setData({
        goods_num: --this.data.goods_num
      });
    }
  },

  /**
   * 跳转购物车页面
   */
  flowCart: function() {
    wx.switchTab({
      url: "../flow/index"
    });
  },

  /**
   * 加入购物车and立即购买
   */
  submit: function(e) {
    let _this = this,
      submitType = e.currentTarget.dataset.type;
    if (submitType === 'buyNow') {
      // 立即购买
      wx.navigateTo({
        url: '../flow/checkout?' + App.urlEncode({
          order_type: 'buyNow',
          goods_id: _this.data.goods_id,
          goods_num: _this.data.goods_num,
          goods_sku_id: _this.data.goods_sku_id
        }),
        success() {
          // 关闭弹窗
          _this.onToggleTrade();
        }
      });
    } else if (submitType === 'addCart') {
      // 加入购物车
      App._post_form('cart/add', {
        goods_id: _this.data.goods_id,
        goods_num: _this.data.goods_num,
        goods_sku_id: _this.data.goods_sku_id,
      }, function(result) {
        App.showSuccess(result.msg);
        _this.setData(result.data);
      });
    }
  },

  /**
   * 浏览商品图片
   */
  previewImages: function(e) {
    let index = e.currentTarget.dataset.index,
      imageUrls = [];
    this.data.detail.image.forEach(function(item) {
      imageUrls.push(item.file_path);
    });
    wx.previewImage({
      current: imageUrls[index],
      urls: imageUrls
    })
  },

  /**
   * 预览Sku规格图片
   */
  previewSkuImage: function(e) {
    wx.previewImage({
      current: this.data.image_path,
      urls: [this.data.image_path]
    })
  },

  /**
   * 跳转到评论
   */
  navigateToComment: function() {
    wx.navigateTo({
      url: './comment/comment?goods_id=' + this.data.goods_id
    })
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage: function() {
    // 构建页面参数
    let params = App.urlEncode({
      'goods_id': this.data.goods_id,
      'referee_id': App.getUserId()
    });
    return {
      title: this.data.detail.goods_name,
      desc: "",
      path: "/pages/goods/index?" + params
    };
  },

  /**
   * 显示分享选项
   */
  openActionsheet(e) {
    // 记录formId
    App.saveFormId(e.detail.formId);
    this.setData({
      'share.show': true
    });
  },

  /**
   * 关闭分享选项
   */
  closeActionSheet() {
    this.setData({
      'share.show': false
    });
  },

  /**
   * 点击分享选项
   */
  clickAction(e) {
    if (e.detail.index === 0) {
      // 显示商品海报
      this.showPoster();
    }
    this.closeActionSheet();
  },

  /**
   * 切换商品海报
   */
  togglePopup() {
    this.setData({
      'share.showPopup': !this.data.share.showPopup
    });
  },

  /**
   * 显示商品海报图
   */
  showPoster: function() {
    let _this = this;
    wx.showLoading({
      title: '加载中',
    });
    App._get('goods/poster', {
      goods_id: _this.data.goods_id
    }, function(result) {
      _this.setData(result.data, function() {
        _this.togglePopup();
      });
    }, null, function() {
      wx.hideLoading();
    });
  },

  /**
   * 保存海报图片
   */
  savePoster: function(e) {
    let _this = this;
    // 记录formId
    App.saveFormId(e.detail.formId);
    wx.showLoading({
      title: '加载中',
    });
    // 下载海报图片
    wx.downloadFile({
      url: _this.data.qrcode,
      success: function(res) {
        wx.hideLoading();
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            });
            // 关闭商品海报
            _this.togglePopup();
          },
          fail: function(err) {
            console.log(err.errMsg);
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              wx.showToast({
                title: "请允许访问相册后重试",
                icon: "none",
                duration: 1000
              });
              setTimeout(function() {
                wx.openSetting();
              }, 1000);
            }
          },
          complete(res) {
            console.log('complete');
            // wx.hideLoading();
          }
        })
      }
    })
  },

  /**
   * 确认购买弹窗
   */
  onToggleTrade(e) {
    let t = typeof e;
    if (typeof e === 'object') {
      // 记录formId
      e.detail.hasOwnProperty('formId') && App.saveFormId(e.detail.formId);
    }
    this.setData({
      showBottomPopup: !this.data.showBottomPopup,
      stars_num:1
    });
  },

  /**
 * 增加数量
 */
  up: function () {
    this.setData({
      stars_num: ++this.data.stars_num
    })
  },

  /**
   * 减少数量
   */
  down: function () {
    if (this.data.stars_num > 1) {
      this.setData({
        stars_num: --this.data.stars_num
      });
    }
  },

  

  //投星星
  castStars:function(e){
    //console.log(e);
    let _this = this;
    let id = e.currentTarget.dataset.id;
    let page_sex = this.data.page_sex;
    let stars_num = this.data.stars_num;
    //console.log(stars_num);
    wx.showModal({
      title: '提示',
      content: '您确定要给TA投星星吗？',
      success(res) {
        if (res.confirm) {
          App._get('Enroll_vote/add', {
            enroll_id: id,
            page_sex: page_sex,
            stars_num: stars_num
          }, function (result) {
            //console.log(result);
            App.showSuccess(result.msg);
            // 关闭弹窗
            _this.onToggleTrade();
            _this.getDetail();
          });
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })

  },

  /**
   * 下拉到底加载数据
   */
  triggerDownLoad: function () {
    console.log(this.data.page);
    console.log(this.data.enroll_vote_res.last_page);
    // 已经是最后一页
    if (this.data.page >= this.data.enroll_vote_res.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    this.getDetail(true, ++this.data.page);
  },

})